package gee

import (
	"fmt"
	"net/http"
)
// 这个别名就离谱起来了 这个是一个函数的别名 而且还是函数声明？
type HandlerFunc func(w http.ResponseWriter, r *http.Request)

// 定义了一个结构体存储Handler
type Engine struct {
	router map[string]HandlerFunc
}

// 怎么找到对应的handler呢 是用方法名连上URL作为key 然后找到对应的Handler
// 但是什么时候key被注册到map中的？New函数中
func (engine *Engine) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	key := request.Method + "-" + request.URL.Path
	if handler, ok := engine.router[key]; ok {
		handler(writer, request)
	} else {
		fmt.Fprintf(writer, "404 NOT FOUND: %s\n", request.URL)
	}
}

// 只是初始化了router 并没有赋值啊
func New() *Engine {
	// 怎么赋值的？？？冒号可还行
	return &Engine{router: make(map[string]HandlerFunc)}
}

func (engine *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
	key := method + "-" + pattern
	engine.router[key] = handler
}

func (engine *Engine) GET(pattern string, handler HandlerFunc) {
	engine.addRoute("GET", pattern, handler)
}

func (engine *Engine) POST(pattern string, handler HandlerFunc) {
	engine.addRoute("POST", pattern, handler)
}

func (engine *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, engine)
}
